package com.oscar.ehome.view.pageview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.oscar.ehome.R;
import com.oscar.ehome.base.fragment.BaseFragment;
import com.oscar.ehome.bean.pagebean.StudyBean;
import com.oscar.ehome.presenter.PagePresenter;
import com.oscar.ehome.utils.pullrefresh.PullToRefreshBase;
import com.oscar.ehome.utils.pullrefresh.PullToRefreshListView;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.view.MyList;
import com.oscar.ehome.utils.view.progressview.ProgressFrameLayout;
import com.oscar.ehome.utils.xrefresh.XRefreshView;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.pageview.adapter.StudyAdapter;
import com.oscar.ehome.view.pageview.view.StudyView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * Created by juxing
 * author: MengWanhe
 * date: On 2017/8/2
 * 学习页
 */

public class StudyFragment extends BaseFragment<StudyView, PagePresenter> implements StudyView, XRefreshView.XRefreshViewListener,
        AdapterView.OnItemClickListener, TextWatcher, ProgressFrameLayout.AgainRequestListener {

    /**
     * 输入框
     */
    @BindView(R.id.serach_study_fragment_edtext)
    EditText serachStudyFragmentEdtext;
    /**
     * 搜索图片
     */
    @BindView(R.id.study_fragment_serach_img)
    ImageView studyFragmentSerachImg;
    /**
     *
     */
    @BindView(R.id.serach_study_fragment)
    RelativeLayout serachStudyFragment;
    /**
     * 下载列表
     */
    @BindView(R.id.study_fragment_buton)
    ImageView studyFragmentButon;
    /**
     * title布局
     */
    @BindView(R.id.study_fragment_title)
    RelativeLayout studyFragmentTitle;
    /**
     * list view
     */
    @BindView(R.id.study_fragment_listview)
    MyList studyFragmentListview;
    /**
     * 无网络布局
     */
    @BindView(R.id.study_fragment_fragment)
    ProgressFrameLayout studyFragmentFragment;
    /**
     * view
     */
    private View view;
    @BindView(R.id.message_refview)
    XRefreshView messageRefview;
    String token = "";
    private int page = 1;//页数
    private int page_size = 20;//每页的条数
    int size = 0;
    String id="";
    List<StudyBean.ListBean> learnList = new ArrayList<>();
    public static long lastRefreshTime;
    PagePresenter presenter;
    StudyAdapter adapter;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_study, null);
        ButterKnife.bind(this, view);
        studyFragmentTitle.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        onClick();
        initView();
        initData();
        getMessage();
        return view;
    }

    @Override
    protected PagePresenter createPresenter() {
        presenter = new PagePresenter(this);
        return presenter;
    }

    /**
     * 判断是否有网
     */
    public boolean isNetWork() {
        boolean netWork = true;
        if (!CommonUtils.isNetConn(getActivity())) {
            netWork = false;
            return netWork;
        }
        return netWork;
    }

    /**
     * 初始化
     */
    public void initView() {
        if(getActivity().getIntent().getStringExtra("id")!=null){
            id=getActivity().getIntent().getStringExtra("id");
        }
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        token = SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getToken();
        serachStudyFragmentEdtext.setHintTextColor(getResources().getColor(R.color.gray_99));
        adapter = new StudyAdapter(getActivity(), learnList, 1);
        studyFragmentListview.setAdapter(adapter);
    }

    /**
     * 加载数据
     */
    public void initData() {
        if (isNetWork()) {
            studyFragmentFragment.stopRefresh();
            studyFragmentListview.setVisibility(View.VISIBLE);
            presenter.getStudyList(token, "20", "1", id,serachStudyFragmentEdtext.getText().toString());
            showLoading();
        } else {
            studyFragmentListview.setVisibility(View.GONE);
            studyFragmentFragment.setVisibility(View.VISIBLE);
            studyFragmentFragment.setLoadFail();
        }

    }

    /**
     * 点击
     */
    public void onClick() {

        studyFragmentListview.setOnItemClickListener(this);
        serachStudyFragmentEdtext.addTextChangedListener(this);
        studyFragmentFragment.setAgainRequestListener(this);
        messageRefview.setXRefreshViewListener(this);
        // 设置是否可以下拉刷新
        messageRefview.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        messageRefview.setPullLoadEnable(false);
        // 设置上次刷新的时间
        messageRefview.restoreLastRefreshTime(lastRefreshTime);
        //当下拉刷新被禁用时，调用这个方法并传入false可以不让头部被下拉
        messageRefview.setMoveHeadWhenDisablePullRefresh(true);
        // 设置时候可以自动刷新
        messageRefview.setAutoRefresh(false);
    }


    /**
     * 设置键盘的搜索事件
     */
    public void getMessage() {
        serachStudyFragmentEdtext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getActivity().getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                    checkMessage();
                }
                return false;
            }
        });
//        serachStudyFragmentEdtext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//                    // 先隐藏键盘
//
//                    ((InputMethodManager) getActivity().getSystemService(getContext().INPUT_METHOD_SERVICE))
//                            .hideSoftInputFromWindow(getActivity().getCurrentFocus()
//                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//                    //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
//                    checkMessage();
//                }
//                return false;
//            }
//        });

    }

    /**
     * 搜索数据
     */
    public void checkMessage() {
        if (TextUtils.isEmpty(serachStudyFragmentEdtext.getText().toString().trim())) {
            Toast.makeText(getActivity(), "请输入要搜索的信息", Toast.LENGTH_SHORT).show();
        } else {
            String s = String.valueOf(page);
            presenter.getStudyList(token, "20", s,id, serachStudyFragmentEdtext.getText().toString());
            showLoading();
        }
    }

    @OnClick({R.id.study_fragment_buton})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.study_fragment_buton://下载记录
                Intent intent = new Intent(getActivity(), DownloadListActivity.class);
                String addapp = new Gson().toJson(learnList);
                intent.putExtra("listData", addapp);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() >= 1) {
            studyFragmentSerachImg.setVisibility(View.GONE);
        } else {
            studyFragmentSerachImg.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String learnType = learnList.get(position).getLearnType();
        if ("video/mp4".equals(learnType)) {//视频
            Intent intent = new Intent(getActivity(), VideoActivity.class);
            intent.putExtra("id", learnList.get(position).getId());
            startActivity(intent);
        } else if ("application/pdf".equals(learnType)) {//PDF
            Intent intent = new Intent(getActivity(), PdfDetialActivity.class);
            intent.putExtra("id", learnList.get(position).getId());
            startActivity(intent);
        } else if ("audio/mp3".equals(learnType)) {//音频
            Intent intent = new Intent(getActivity(), FrequencyActivity.class);
            intent.putExtra("id", learnList.get(position).getId());
            startActivity(intent);
        }
    }

    @Override
    public void getstudyList(StudyBean result) {
        dismissLoading();
        messageRefview.stopRefresh();
        if (result != null) {
            if (page == 1) {
                learnList.clear(); // 将原有的内容清空
            }
            learnList = result.getList();
            size = learnList.size();
            if (size < page_size && learnList.size() > 0) {
                messageRefview.stopLoadMore();
                studyFragmentListview.setVisibility(View.VISIBLE);

            }
            studyFragmentFragment.stopRefresh();
            if (size == 0) {
                studyFragmentFragment.setNoResult();
                studyFragmentListview.setVisibility(View.GONE);
            }
            adapter.setLists(learnList, 1);
        }
    }

    @Override
    public void erroy() {
        dismissLoading();
        messageRefview.stopRefresh();
        studyFragmentFragment.setNoResult();
        studyFragmentListview.setVisibility(View.GONE);
        ToastUtil.show(getActivity(), getString(R.string.erry));
    }

    @Override
    public void erry(String result) {
        dismissLoading();
        messageRefview.stopRefresh();
        messageRefview.stopRefresh();
        studyFragmentFragment.setNoResult();
        studyFragmentListview.setVisibility(View.GONE);
        Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
        if (result.contains("过期")) {
            getActivity().getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(getActivity()).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(getActivity()).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
            getActivity().finish();
        }
    }



    @Override
    public void againRequest() {
        if (isNetWork()) {
            initData();
        } else {
            ToastUtil.show(getActivity(), R.string.pull_to_refresh_network_error);
        }
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onRefresh(boolean isPullDown) {
        lastRefreshTime = messageRefview.getLastRefreshTime();
        messageRefview.restoreLastRefreshTime(lastRefreshTime);
        page = 1;
        String s = String.valueOf(page);
        presenter.getStudyList(token, "20", s, id,serachStudyFragmentEdtext.getText().toString());
        showLoading();
    }

    @Override
    public void onLoadMore(boolean isSilence) {
        page++;
        String s = String.valueOf(page);
        presenter.getStudyList(token, "20", s,id, serachStudyFragmentEdtext.getText().toString());
        showLoading();
    }

    @Override
    public void onRelease(float direction) {

    }

    @Override
    public void onHeaderMove(double headerMovePercent, int offsetY) {

    }
}
